using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace Acms.AcmsControls
{
    [ToolboxData("<{0}:UserLogonControl runat=server></{0}:UserLogonControl>")]
    public class UserLogonControl : CompositeControl
    {
        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.Div;
            }
        }

        private string errorMessageClass = "errorMessage";
        public string ErrorMessageClass
        {
            get { return errorMessageClass; }
            set { errorMessageClass = value; }
        }

        private string registerUrl = "Register.aspx";
        public string RegisterUrl
        {
            get { return registerUrl; }
            set { registerUrl = value; }
        }

        private string forgottenPasswordUrl = "ForgottenPassword.aspx";
        public string ForgottenPasswordUrl
        {
            get { return forgottenPasswordUrl; }
            set { forgottenPasswordUrl = value; }
        }

        protected override object SaveViewState()
        {
            ViewState["ForgottenPasswordUrl"] = ForgottenPasswordUrl;
            ViewState["RegisterUrl"] = RegisterUrl;
            return base.SaveViewState();
        }

        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            ForgottenPasswordUrl = ViewState["ForgottenPasswordUrl"] as string;
            RegisterUrl = ViewState["RegisterUrl"] as string;
        }
	

        TextBox username;
        TextBox password;
        RequiredFieldValidator valUsernameReq;
        RequiredFieldValidator valPasswordReq;
        Button btnLogon;
        CheckBox cbRemember;
        bool invalidPassword;
        bool invalidUsername;

        protected override void CreateChildControls()
        {
            this.Controls.Clear();

            username = new TextBox();
            username.ID = "username";
            this.Controls.Add(username);

            valUsernameReq = new RequiredFieldValidator();
            valUsernameReq.ErrorMessage = "!Required";
            valUsernameReq.ControlToValidate = username.ID;
            valUsernameReq.ValidationGroup = this.ClientID;
            this.Controls.Add(valUsernameReq);

            password = new TextBox();
            password.ID = "password";
            password.TextMode = TextBoxMode.Password;
            this.Controls.Add(password);

            valPasswordReq = new RequiredFieldValidator();
            valPasswordReq.ErrorMessage = "!Required";
            valPasswordReq.ControlToValidate = password.ID;
            valPasswordReq.ValidationGroup = this.ClientID;
            this.Controls.Add(valPasswordReq);

            cbRemember = new CheckBox();
            cbRemember.ID = "cbRemember";
            this.Controls.Add(cbRemember);

            btnLogon = new Button();
            btnLogon.ID = "btnLogon";
            btnLogon.Text = "Logon";
            btnLogon.Click += new EventHandler(btnLogon_Click);
            btnLogon.ValidationGroup = this.ClientID;
            this.Controls.Add(btnLogon);

            base.CreateChildControls();
        }

        void btnLogon_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                Acms.Bll.UserSecurity user = Acms.Bll.UserSecurity.GetByUserName(username.Text);
                if (user != null)
                {
                    if (user.AuthenticatePassword(password.Text))
                    {
                        string siteRoot = Page.Request.ServerVariables["Server_Name"];
                        if (Page.Request.ApplicationPath != "/")
                            siteRoot += Page.Request.ApplicationPath;

                        List<Acms.Bll.UserRole> roles = user.GetRoles(siteRoot);

                        //user.LastLogin = DateTime.Now;
                        System.Web.Security.FormsAuthentication.SetAuthCookie(username.Text, cbRemember.Checked);
                    }
                    //invalid password
                    invalidPassword = true;
                }
                //invalid username
                invalidUsername = true;
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            //Page.RegisterRequiresRaiseEvent(this);
            base.OnPreRender(e);
        }

        public override void RenderControl(HtmlTextWriter writer)
        {
            //wrapper div
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            if (Page.Request.IsAuthenticated)
            {
                writer.Write("You are logged in as '{0}'.", Page.User.Identity.Name); 
            }
            else
            {

                if (invalidUsername || invalidPassword)
                {
                    RenderErrorMessage(writer);
                }

                //wrapper ul
                writer.RenderBeginTag(HtmlTextWriterTag.Ul);

                //user name
                writer.RenderBeginTag(HtmlTextWriterTag.Li);
                RenderUsername(writer);
                writer.RenderEndTag();

                //password
                writer.RenderBeginTag(HtmlTextWriterTag.Li);
                RenderPassword(writer);
                writer.RenderEndTag();

                //remember me
                writer.RenderBeginTag(HtmlTextWriterTag.Li);
                RenderRememberMe(writer);
                writer.RenderEndTag();

                //button
                writer.RenderBeginTag(HtmlTextWriterTag.Li);
                RenderButton(writer);
                writer.RenderEndTag();

                //register
                writer.RenderBeginTag(HtmlTextWriterTag.Li);
                RenderRegisterLink(writer);
                writer.RenderEndTag();

                //forgotten password
                writer.RenderBeginTag(HtmlTextWriterTag.Li);
                RenderForgottenPasswordLink(writer);
                writer.RenderEndTag();

                writer.RenderEndTag();
            }
            writer.RenderEndTag();
        }

        private void RenderUsername(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.For, username.ClientID);
            writer.RenderBeginTag(HtmlTextWriterTag.Label);
            writer.Write("Username:");
            writer.RenderEndTag();
            username.RenderControl(writer);
            valUsernameReq.RenderControl(writer);
        }

        private void RenderPassword(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.For, password.ClientID);
            writer.RenderBeginTag(HtmlTextWriterTag.Label);
            writer.Write("Password:");
            writer.RenderEndTag();
            password.RenderControl(writer);
            valPasswordReq.RenderControl(writer);
        }

        private void RenderRememberMe(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.For, password.ClientID);
            writer.RenderBeginTag(HtmlTextWriterTag.Label);
            writer.Write("Remember me next time?");
            writer.RenderEndTag();
            cbRemember.RenderControl(writer);
        }

        private void RenderButton(HtmlTextWriter writer)
        {
            btnLogon.RenderControl(writer);
        }

        private void RenderErrorMessage(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Class, ErrorMessageClass);
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            writer.Write("Invalid username and/or password. Please try again or use forgotten password.");
            writer.RenderEndTag();
        }

        private void RenderRegisterLink(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Href, Page.ResolveClientUrl(RegisterUrl));
            writer.RenderBeginTag(HtmlTextWriterTag.A);
            writer.Write("Register");
            writer.RenderEndTag();
        }

        private void RenderForgottenPasswordLink(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Href, Page.ResolveClientUrl(ForgottenPasswordUrl));
            writer.RenderBeginTag(HtmlTextWriterTag.A);
            writer.Write("Forgotten Password");
            writer.RenderEndTag();
        }
    }
}
